/*
 * test_levent_c.cpp
 *
 *  Created on: Mar 31, 2014
 *      Author: killerg
 */

#include "net.h"
#include "share/clock.h"
#include <stdio.h>
#include <unistd.h>
#include <event2/dns.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>

#include <set>
#include <map>
using namespace std;

static map<conn_t*, int> s_conns;

static void conn_connect_cb(conn_t* conn)
{
	s_conns[conn] = 0;
	printf("conn_connect_cb\n");
	for (int i=0; i<100; ++i) {
		evbuffer_add_printf(bufferevent_get_output(conn->bev), "hello");
	}
}
static void conn_disconnect_cb(conn_t* conn)
{
	s_conns.erase(conn);
	if (s_conns.empty()) {
		event_base_loopexit(bufferevent_get_base(conn->bev), NULL);
	}
	printf("conn_disconnect_cb\n");
}
static void conn_data_cb(conn_t* conn)
{
	printf("conn_data_cb\n");
	evbuffer_add_buffer(bufferevent_get_output(conn->bev), bufferevent_get_input(conn->bev));
	//evbuffer_write(bufferevent_get_input(conn->bev), 1);
	s_conns[conn] = s_conns[conn] + 1;
	if (s_conns[conn] >= 100) {
		conn_disconnect(conn);
	}
}

int test_levent_c()
{

    event_base*base = event_base_new();
    evdns_base* dns_base = evdns_base_new(base, 1);

    for (int i=0; i<100; ++i) {
        start_connect(base, dns_base,
        		"localhost", 9876,
        		conn_connect_cb,
        		conn_disconnect_cb,
        		conn_data_cb);
    }

    my_clock_t clock;

	clock.init(500);
    while (true) {
    	clock.begin_update();
       	event_base_loop(base, EVLOOP_NONBLOCK);
    	clock.end_update();
    	clock.wait_frame();
    }
    clock.destroy();

    evdns_base_free(dns_base, 1);
    event_base_free(base);

    return 0;
}
